package com.fs.web.yz.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fs.common.pojo.CheckNote;
import com.fs.common.pojo.Recipes;
import com.fs.common.pojo.RecipesTemplate;
import com.fs.web.base.enums.CodeEnum;
import com.fs.web.base.vo.JsonResponse;
import com.fs.web.yz.service.ICheckRecipesService;
import com.fs.web.yz.service.IRecipesService;
import com.fs.web.yz.service.IRecipesTemplateService;
import com.fs.web.yz.utils.RecipesUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 食谱
 */

@Slf4j
@Controller
@RequestMapping("/console/recipesTemplate/rewrite")
public class RecipesTemplateController {

    @Autowired
    private IRecipesService recipesService;
    @Autowired
    private IRecipesTemplateService templateService;
    @Autowired
    private ICheckRecipesService checkRecipesService;

    /**
     * 创建菜谱模板标识 0可创建菜谱模板 1正在创建菜谱模板 2创建菜谱模板异常
     */
    private static int createAllFlag = 0;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private String[] createAllFlagArr={"可创建菜谱模板", "正在创建菜谱模板", "创建菜谱模板异常"};

    /**
     * 生成一个月的菜谱模板
     */
    @ResponseBody
    @RequestMapping("/createAll")
    public JsonResponse createAllRecipesTemplate(){
        try {
            if (createAllFlag != 1){
                RecipesUtils ru = new RecipesUtils();
                if (logger.isInfoEnabled()) {
                    logger.info("Recipes assign type start!");
                }
                //获取全部菜谱, 并根据早 中 晚 加进行分类保存
                List<Recipes> recipesList = recipesService.list();
                for (Recipes r : recipesList) {
                    ru.assignRecipes(r);
                }
                if (logger.isInfoEnabled()) {
                    logger.info("Recipes assign type finish!");
                }
                createAllFlag = 1;
                //清理旧数据
                templateService.clearRecipesTemplate();
                if (logger.isInfoEnabled()) {
                    logger.info("the old data of template was clear finish!");
                }
                //1-28全部食谱模板
                for (int begin = RecipesUtils.Month_First, end = RecipesUtils.Month_Last + 1; begin < end; begin++) {
                    Map<String, Collection<RecipesTemplate>> templateMap = ru.getDayTemplate(begin);
                    for (String key : templateMap.keySet()) {
                        if (logger.isInfoEnabled()) {
                            logger.info(key + "batch save start!");
                        }
                        templateService.saveBatch(templateMap.get(key));
                        if (logger.isInfoEnabled()) {
                            logger.info(key + "batch save finish!");
                        }
                    }
                }
                createAllFlag = 0;
                return JsonResponse.success();
            }else{
                return JsonResponse.error(createAllFlagArr[createAllFlag]);
            }
        }catch (Exception e){
            createAllFlag = 2;
            logger.error(createAllFlagArr[createAllFlag]);
            log.error(e.getMessage(), e);
            return JsonResponse.error(CodeEnum.EX999);
        }
    }

    @ResponseBody
    @RequestMapping("/getCreateAllFlag")
    public JsonResponse getCreateAllFlag(){
        Map<String, Object> rtn = new HashMap<>();
        rtn.put("flag", createAllFlag);
        rtn.put("info", createAllFlagArr[createAllFlag]);
        return JsonResponse.success(rtn);
    }

    /**
     * 将某个菜谱加入到菜谱模板中
     * @param recipesId
     * @return
     */
    @ResponseBody
    @RequestMapping("/addOne")
    public JsonResponse addOneRecipesTemplate(@RequestParam String recipesId){
        try{
            Recipes r = recipesService.getById(recipesId);
            if (r != null){
                QueryWrapper<RecipesTemplate> tplQuery = new QueryWrapper();
                tplQuery.eq("recipes_id", recipesId);
                int cnt = templateService.count(tplQuery);
                if (cnt == 0) {
                    addRecipes(r);
                    return JsonResponse.success();
                }else{
                    return JsonResponse.error("Recipes template had exist!!! - id" + recipesId);
                }
            }else{
                return JsonResponse.error("Recipes not exist!!! - id" + recipesId);
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
            return JsonResponse.error(CodeEnum.EX999);
        }
    }

    /**
     * 将某个菜谱修改后，删除原来的记录信息，重新加入到菜谱模板中
     * @param recipesId
     * @return
     */
    @ResponseBody
    @RequestMapping("/editOne")
    public JsonResponse editOneRecipesTemplate(@RequestParam String recipesId){
        try{
            Recipes r = recipesService.getById(recipesId);
            if (r != null){
                QueryWrapper<RecipesTemplate> tplQuery = new QueryWrapper();
                tplQuery.eq("recipes_id", recipesId);
                boolean flag = templateService.remove(tplQuery);
                if (flag){
                    addRecipes(r);
                    return JsonResponse.success();
                }else{
                    return JsonResponse.error("Recipes template remove fail!!! - id" + recipesId);
                }
            }else{
                return JsonResponse.error("Recipes not exist!!! - id" + recipesId);
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
            return JsonResponse.error(CodeEnum.EX999);
        }
    }

    /**
     * 将某个菜谱加入到菜谱模板中
     * @param r 菜谱信息
     * @return
     */
    private void addRecipes(Recipes r){
        RecipesUtils ru = new RecipesUtils();
        //根据早 中 晚 加进行分类保存
        ru.assignRecipes(r);
        int begin = RecipesUtils.Month_First, end = RecipesUtils.Month_Last + 1;
        String days = r.getDay();
        if (days.contains("-")) {
            String[] num = days.split("-");
            begin = Integer.parseInt(num[0]);
            end = Integer.parseInt(num[1]) + 1;
        } else {
            begin = Integer.parseInt(days);
            end = Integer.parseInt(days) + 1;
        }
        //1-28全部食谱模板
        for (int i = begin; i < end; i++) {
            Map<String, Collection<RecipesTemplate>> templateMap = ru.getDayTemplate(i);
            if (templateMap != null && templateMap.size() > 0) {
                for (String key : templateMap.keySet()) {
                    if (logger.isInfoEnabled()) {
                        logger.info(key + "save start!");
                    }
                    templateService.saveBatch(templateMap.get(key));
                    if (logger.isInfoEnabled()) {
                        logger.info(key + "save finish!");
                    }
                }
            }
        }
    }

    /**
     * 根据检查记录生成一个月的菜谱
     */
    @ResponseBody
    @RequestMapping("/createCheckRecipes")
    public JsonResponse createCheckRecipes(@RequestParam String checkId){
        CheckNote cn = new CheckNote();
        try {
            cn = cn.selectById(checkId);
            if (cn != null) {
                checkRecipesService.createCheckRecipesForCheck(cn);
                return JsonResponse.success();
            }else{
                return JsonResponse.error(CodeEnum.EX400);
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
            return JsonResponse.error(CodeEnum.EX999);
        }
    }

}
